package cn.itlight.org.service.impl;

import cn.itlight.basic.constant.BaseConstants;
import cn.itlight.basic.exception.BusinessException;
import cn.itlight.basic.utils.BaiduAuditUtils;
import cn.itlight.org.domain.Employee;
import cn.itlight.org.domain.Shop;
import cn.itlight.org.domain.ShopAuditLog;
import cn.itlight.org.mapper.EmployeeMapper;
import cn.itlight.org.mapper.ShopAuditLogMapper;
import cn.itlight.org.mapper.ShopMapper;
import cn.itlight.org.service.IEmployeeService;
import cn.itlight.org.service.IShopService;
import cn.itlight.basic.service.impl.BaseServiceImpl;
import cn.itlight.basic.vo.ShopVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tomliu
 * @since 2022-07-01
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void settlement(Shop shop) {
        Employee admin = shop.getAdmin();
        String phone = admin.getPhone();
        String smsCodeValue = admin.getSmsCodeValue();

        // 1.判断必要参数是否为空，以名称举例
        if (StringUtils.isEmpty(shop.getName())){
            throw new BusinessException("参数不能为空，请重新输入！");
        }
        // 2.两次密码是否一致
        if (!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BusinessException("两次密码不一致，请重新输入！");
        }
        Boolean boo = BaiduAuditUtils.TextCensor(shop.getName());
        if (!boo){
            throw new BusinessException("店铺名有违规词汇，请修改后再次申请！");
        }
        // 4.查询管理员已经注册过，并且还绑定了某个店铺，这种情况我们认为你不符合我们业务要求，抛出异常
        Employee emp = employeeMapper.loadByUserName(admin.getUsername());
        if(shop.getId()==null){
            // 3.查询店铺是否存在,根据店铺名称查询
            Shop loadShopTmp = shopMapper.loadByName(shop.getName());
            if (loadShopTmp != null){
                throw new BusinessException("店铺已注册，请更换店铺信息！");
            };
            if (emp != null && emp.getShopId() != null){
                throw new BusinessException("该管理员已绑定店铺，请更换其他管理员！");
            }
        }
        if (emp != null && emp.getShopId() != shop.getId()){
            throw new BusinessException("该管理员已绑定店铺，请更换其他管理员！");
        }
        // 1.为空校验
        String phoneCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_PREFIX + phone;
        Object phoneCodeValueRedis = redisTemplate.opsForValue().get(phoneCodeKey);
        // 2.验证手机号是否一致，验证码是否过期
        if (phoneCodeValueRedis == null){
            throw new BusinessException("验证码已失效，请重试！");
        }
        // 3.判断验证码是否正确
        String split = phoneCodeValueRedis.toString().split(":")[1];
        if (!split.equalsIgnoreCase(smsCodeValue)){
            throw new BusinessException("验证码错误，请重试！");
        }


        // 5.管理员没注册，那么注册管理员
        if (emp == null){
            employeeService.save(admin);
            emp = admin;
        }
        // 6.如果走到这里，那么管理员绝对已经注册过了
        // 6.1.将管理员的主键设置到店铺的外键
        shop.setAdminId(emp.getId());
        // 6.2.保存店铺,一定要返回主键
        if(shop.getId()==null){
            shopMapper.save(shop);
        }else {
            shop.setState(0);
            shopMapper.update(shop);
        }

        // 6.3.将店铺的主键设置到管理员的外键
        emp.setShopId(shop.getId());
        // 6.4.修改员工数据
        employeeService.update(emp);
    }

    /*
    * @Title: pass
    * @Description: 通过
    * @Author: TomLiu
    * @Version: 1.0
    * @Date:  2022/7/2 16:39
    * @Parameters:
    * @Return
    */
    @Override
    public void pass(ShopAuditLog shopAuditLog) {
        // 修改状态为未激活
        Long shopId = Long.valueOf(shopAuditLog.getShopId());
        Shop shop = shopMapper.loadById(shopId);
        shop.setState(2);
        shopMapper.update(shop);
        // 设置操作者
        shopAuditLog.setAuditId(325);

        // 保存在数据库
        shopAuditLogMapper.save(shopAuditLog);
        // 调用发送工具
        try {
            // 1.创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("1406775073@qq.com");
            helper.setSubject("宠物乐园店铺入驻结果通知");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>亲，您的店铺入驻申请信息我平台已审核通过，请点击下方链接激活店铺</h1>"+
                    "店铺激活链接：<a href='http://localhost:8080/shop/pass/"+shopId+"'>点我激活店铺</a>",true);
            // 5.设置收件人
            helper.setTo("1406775073@qq.com");
            // 6.发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /*
    * @Title: reject
    * @Description: 驳回
    * @Author: TomLiu
    * @Version: 1.0
    * @Date:  2022/7/2 16:39
    * @Parameters:
    * @Return
    */
    @Override
    public void reject(ShopAuditLog shopAuditLog) {
        // 修改状态为驳回
        Long shopId = Long.valueOf(shopAuditLog.getShopId());
        Shop shop = shopMapper.loadById(shopId);
        shop.setState(-1);
        shopMapper.update(shop);
        // 设置操作者
        shopAuditLog.setAuditId(325);
        // 保存在数据库
        shopAuditLogMapper.save(shopAuditLog);
        // 调用发送工具
        try {
            // 1.创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("1406775073@qq.com");
            helper.setSubject("宠物乐园店铺入驻结果通知");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>亲，您的店铺入驻申请信息我平台已审核，但是因为内容不合规被驳回，请修改店铺信息后，再次申请</h1>"+
                    "店铺信息修改链接：<a href='http://localhost:8081/#/shopRegister2?shopId="+shopAuditLog.getShopId()+"'>点我修改店铺信息</a>",true);
            // 5.设置收件人
            helper.setTo("1406775073@qq.com");
            // 6.发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void denial(ShopAuditLog shopAuditLog) {
        // 修改状态为拒绝
        Long shopId = Long.valueOf(shopAuditLog.getShopId());
        Shop shop = shopMapper.loadById(shopId);
        shop.setState(-2);
        shopMapper.update(shop);
        // 设置操作者
        shopAuditLog.setAuditId(325);
        // 保存在数据库
        shopAuditLogMapper.save(shopAuditLog);
        // 调用发送工具
        try {
            // 1.创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("1406775073@qq.com");
            helper.setSubject("宠物乐园店铺入驻结果通知");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>亲，您的店铺入驻申请信息我平台已审核，因为不符合规范不能入驻</h1>"+
                    "拒绝原因："+shopAuditLog.getNote(),true);
            // 5.设置收件人
            helper.setTo("1406775073@qq.com");
            // 6.发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void addList(List<Shop> shops) {
        shopMapper.addList(shops);
    }

    @Override
    public Map<String, Object> echarts() {
        List<ShopVo> shopVos = shopMapper.echarts();
//        List<Integer> states = shopVos.stream().map(ShopVo::getState).collect(Collectors.toList());
//        List<Integer> counts = shopVos.stream().map(ShopVo::getCount).collect(Collectors.toList());
        List<String> states = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        for (ShopVo shopVo : shopVos) {
            Integer state = shopVo.getState();
            String sta = "";
            System.out.println(state);
            if (state == -2){
                sta = "拒绝";
            } else if (state == -1){
                sta = "驳回";
            } else if (state == 0){
                sta = "待审核";
            } else if (state == 1){
                sta = "已审核";
            } else if (state == 2){
                sta = "待激活";
            }

            states.add(sta);
            counts.add(shopVo.getCount());
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("x", states);
        map.put("y", counts);
        return map;
    }



}
